package com.house.security;

import com.house.entity.User;
import com.house.service.user.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

/**自定义认证实现
 * @author:lzq
 * @date: 2018/5/25 12:17
 */
public class AuthProvider implements AuthenticationProvider {

    private final Md5PasswordEncoder passwordEncoder = new Md5PasswordEncoder();

    @Autowired
    private IUserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //SpringSecurity里的token信息
        String name = authentication.getName();
        String password = (String)authentication.getCredentials();

        User user = userService.findUserByName(name);
        if(user==null){
            throw new AuthenticationCredentialsNotFoundException("authError");
        }
        //验证用户输入密码是否正确
        if (this.passwordEncoder.isPasswordValid(user.getPassword(), password, user.getId())) {
            return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());//验证成功之后密码设为空
        }
        throw new BadCredentialsException("authError");
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}
